package com.dk.common;

import com.dk.exception.SimpleException;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 *
 * @author: A11181121050450
 * @date: 2020-04-20 14:43
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Object globalHandler(Exception e, HttpServletRequest request, HttpServletResponse response){
        log.error(e.getMessage(),e);
        String unifyMsg = "未知异常，请联系管理员";
        if(HttpMethod.GET.matches(request.getMethod())){
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            return alert(unifyMsg);
        }else{
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            BaseVo baseVo = new BaseVo("-1",unifyMsg);
            return baseVo;
        }
    }

    @ExceptionHandler(SimpleException.class)
    @ResponseStatus(HttpStatus.OK)
    public Object simpleHandler(SimpleException e, HttpServletRequest request, HttpServletResponse response){
        log.error(e.getMessage(),e);
        if(HttpMethod.GET.matches(request.getMethod())){
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            return alert(e.getMessage());
        }else{
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            BaseVo baseVo = new BaseVo(e.getCode(),e.getMessage());
            return baseVo;
        }
    }

    @ExceptionHandler(ClientAbortException.class)
    public void clientAbortException(ClientAbortException e) throws ClientAbortException {
        throw e;
    }

    private String alert(String msg){
        return "<html><meta content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" name=\"viewport\" /><body>" + msg + "</body></html>";
    }
}
